package com.wrupple.muba.widget.client.widgets.panels.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.gwt.view.client.Range;

public class LayoutDataPanelDelegate<T> {

	private LayoutDataPanel<T> layoutDataPanel;
	private ArrayList<T> visibleData;
	private int rangeLength=25;

	public LayoutDataPanelDelegate(LayoutDataPanel<T> layoutDataGrid) {
		this.layoutDataPanel = layoutDataGrid;
		visibleData = new ArrayList<T>();
	}

	public void setRowData(int start, List<? extends T> values) {
		 replaceOrAdd(start,values);
		
		 layoutDataPanel.render(start, values);
	}
	

	

	public boolean setVisibleRange(int start, int length) {
		assert start==0:"This data widget only supports starting from 0";
		int visibleDataSize = visibleData.size();
		if(visibleDataSize==length){
			//nothing to do
			return false;
		}else{
			if(length>visibleDataSize){
				//we need more data!
				rangeLength = length;
			}else{
				//trim data
				layoutDataPanel.trim(length+1,visibleDataSize-1);
				visibleData=(ArrayList<T>) visibleData.subList(0, length);
				rangeLength = visibleData.size();
			}
			return true;
		}
		
	}

	public void setRowCount(int count, boolean isExact) {
		assert isExact : "This widget only supports exact row counts";
		if(count==visibleData.size()){
			//we are ok!
		}else{
			setVisibleRange(0, count);
		}
	}

	private void replaceOrAdd(int start, List<? extends T> values) {
		int indexToAddInto;
		T element;
		for (int i = 0; i < values.size(); i++) {
			indexToAddInto = i + start;
			element = values.get(i);
			if (indexToAddInto == visibleData.size()) {
				visibleData.add(element);
			} else {
				visibleData.set(indexToAddInto, element);
			}
		}
	}



	public int getTotalElementsCount() {
		return visibleData.size();
	}

	public Range getVisibleRange() {
		return new Range(0,  rangeLength);
	}

	public T getVisibleItem(int indexOnPage) {
		return visibleData.get(indexOnPage);
	}

	public int getVisibleItemCount() {
		return visibleData.size();
	}

	public List<T> getVisibleItems() {
		return Collections.unmodifiableList(visibleData);
	}

	public void clear() {
		visibleData.clear();
	}


}
